<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider v-model:collapsed="collapsed" collapsible theme="light">
      <div class="logo">
        <transition name="el-fade-in">
          <div class="transition-box" v-show="collapsed == false">
            <a-image :width="100" style="margin-left: 32px; margin-top: 4px" src="/q3.png"/>
          </div>
        </transition>
        <transition name="el-fade-in">
          <div class="transition-box" v-show="collapsed == true">
            <a-image
                :width="60"
                style="margin-left: -10px; margin-top: 0px;"
                src="/logo.png"
            />
          </div>
        </transition>

      </div>
      <a-menu v-model:selectedKeys="selectedKeys" theme="light" mode="inline">
        <a-sub-menu key="duty">
          <template #title>
            <span>
              <deployment-unit-outlined style="color: green"/>
<!--              <field-time-outlined/>-->
              <span>值班管理</span>
            </span>
          </template>
          <a-menu-item key="timeSet" @click="goTimeSet"> 时间配置 </a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="manage">
          <template #title>
            <span>
              <audit-outlined style="color:black;"/>
              <span>信息审核</span>
            </span>
          </template>
          <a-menu-item key="extra" @click="goExtraManage">
            追加审核
          </a-menu-item>
          <a-menu-item key="visit" @click="goVisitManage">
            初访审核与管理
          </a-menu-item>
        </a-sub-menu>
        <a-menu-item key="info" @click="goInfoManage">
          <setting-outlined style="color: sandybrown"/>
          <span>信息维护</span>
        </a-menu-item>
        <a-menu-item key="statistic" @click="goStatistics">
          <bar-chart-outlined style="color: red"/>
          <span>统计分析</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>


    <a-layout>
      <div>
        <a-layout-header style="
          background: #fff;
          padding: 0;
          box-shadow: 1px 1px 1px #888888;
          height: 70px;
        " bordered>
          <div style="display:table;width: 100%;vertical-align: middle;height: 70px">
            <div style="
          height: 70px;
          display:table-cell;word-wrap: break-word;
          ">
              <a-page-header style="border: none;width:78%;position: absolute;margin-bottom: 23.5px" title="中心管理员"
                             sub-title="here is admin"/>
            </div>
            <div class="myop" style="
          width:14%;
          display:table-cell;
          height:70px;
          word-wrap: break-word;
          ">
              <a-menu mode="horizontal" @select="selectCurrUser">
                <a-sub-menu>
                  <template #title>
                    <a-avatar v-if="currImageUrl" @click="setAvatar" :src="currImageUrl"
                              style="vertical-align: middle"/>
                    <span v-else style="vertical-align: middle;
                    cursor: pointer">
                      <smile-outlined/>
                      <a @click="setAvatar" style="font-size: 14px; color: #aa0000">
                        设置头像
                      </a>
                    </span>
                    <span>&nbsp;&nbsp;</span>
                    <span style="vertical-align: middle">{{ currUser.userId }}
                      <b v-if="currUser.userName" style="color:#0458a7;">[
                        {{ currUser.userName }}
                      ]</b>
                    </span>
                  </template>
                  <a-menu-item key="password">密码修改</a-menu-item>
                  <a-menu-item key="exit">退出系统</a-menu-item>
                </a-sub-menu>
              </a-menu>
            </div>
          </div>
        </a-layout-header>
      </div>


      <a-modal v-model:visible="visible" title="设置新头像" @ok="execUpload" style="width:1000px">
        <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
                  :before-upload="() => false" @change="handleChange" @preview="handlePreview">

          <a-avatar v-if="imageUrl" @click="setAvatar" :src="imageUrl" shape="circle" style="vertical-align: middle"
                    :size="118"/>
          <!-- <img :src="imageUrl" /> -->
          <div v-else>
            <plus-outlined/>
            <div class="ant-upload-text">选择图片或拖动至此处</div>
          </div>
        </a-upload>
        <!--
        <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal> -->
      </a-modal>


      <a-layout-content style="margin-top:16px">
        <router-view></router-view>
      </a-layout-content>

      <a-layout-footer style="text-align: center">
        XJTU SE 2022 Created&ensp;by&ensp;GROUP&ensp;
        <span style="color:orangered;">
          <b>XJTU-07</b>
        </span>
      </a-layout-footer>
    </a-layout>
  </a-layout>


</template>

<script setup>
////////////////////////////////////////////
import {reactive, ref} from "vue";
import {
  post, setLocalToken,
  get,
  del,
  getBlob,
  tip,
  removeLocalToken,
  getLocalToken,
} from "@/common";
import {useRouter} from "vue-router";
import {message} from "ant-design-vue";
//import {DownloadOutlined} from "";

////////////////////////////////////////////
const router = useRouter();


const selectedKeys = ref([])

const goRole = () => {
  router.push({path: '/admin/role'})
};

const goStudent = () => {
  router.push({path: '/admin/user'})
};


//获得当前用户
const currUser = ref({});

const getCurrUser = () => {
  get("/curr_user/get_curr-user", {}, {loading: false}).then((res) => {
    currUser.value = res.data;
    console.log("当前用户");
    console.log(currUser.value);
    getAvatar();
  });
};
getCurrUser();

//获得头像
const currImageUrl = ref("");
const getAvatar = () => {
  if (!currUser.value || !currUser.value.avatar) {
    return;
  }
  console.log("开始获取头像")
  getBlob(
      "/avatar/" + currUser.value.avatar,
      {},
      {loading: false}
  ).then((blob) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      currImageUrl.value = reader.result;
    });
    reader.readAsDataURL(blob);


    downloadHref.value=URL.createObjectURL(blob);
    downloadFileName.value=currUser.value.avatar;

    // const fileName = '帮助文档.jpg';
    // const down = document.createElement('a');
    // down.download = fileName;
    // down.style.display = 'none';//隐藏,没必要展示出来
    // down.href = URL.createObjectURL(blob);
    // document.body.appendChild(down);
    // down.click();
    // URL.revokeObjectURL(down.href); // 释放URL 对象
    // document.body.removeChild(down);//下载完成移除
  });
};
const downloadHref = ref("");
const downloadFileName = ref("");

const avatarFile = ref(null);
const imageUrl = ref("");
const visible = ref(false);


const setAvatar = () => {
  visible.value = true;
};


const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleChange = (info) => {
  avatarFile.value = info.file;
  // previewImage.value = getBase64(info.file);
  // previewVisible = true;
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    imageUrl.value = reader.result;
  });
  reader.readAsDataURL(info.file);
};

const handlePreview = async file => {
  if (!file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = error => reject(error);
  });
}

const execUpload = () => {
  const token = getLocalToken();
  console.log("执行头像上传，携带Token :");
  console.log(token);
  if (!avatarFile.value) {
    tip.error("请选择头像！");
    return;
  }
  const formData = new FormData();
  formData.append("avatar", avatarFile.value);
  post("/avatar/setavatar", formData).then((res) => {
    tip.success("头像设置成功！");
    visible.value = false;
    getCurrUser();
  });
};

const selectCurrUser = ({item, key, selectedKeys}) => {
  switch (key) {
    case "exit": //退出系统
      removeLocalToken();
      tip.success("您已成功退出系统，请重新登录！");
      router.push({path: "/"});
      break;

    case "password": //修改密码简易版
      router.push({path: "/security/UpdatePassword"});
      break;
  }
};
////////////////////////////////////////////
const collapsed = ref(false);


const goVisitManage = () => {
  router.push({path: "/admin/VisitManage"});
};

const goInfoManage = () => {
  router.push({path: "/admin/InfoManage"});
};

const goExtraManage = () => {
  router.push({path: "/admin/ExtraManage"});
};

const goTimeSet = () => {
  router.push({path: "/admin/TimeSet"});
};

const goStatistics = () => {
  router.push({path: "/admin/Statistics"});
};


////////////////////////////////////////////

</script>

<style>
.logo {
  height: 60px;
  margin: 16px;
  background: lightyellow;
}

.site-layout .site-layout-background {
  background: #fff;
}

[data-theme="dark"] .site-layout .site-layout-background {
  background: #141414;
}
</style>